package com.config;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 统计字符数 字数
 * @return [统计字符数,字数,运行时间]
 */
@Component
public class DocUtil {

    public static int getMSWordsCount(String content) {
        //中文单词
        content = content.replace("\n", "");
        String cnWords = content.replaceAll("[^(\\u4e00-\\u9fa5，。《》？；’‘：“”【】、）（……￥！·)]", "");
        int cnWordsCount = cnWords.length();
        //非中文单词
        String noCnWords = content.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":><?\\[\\])]", " ");
        int noCnWordsCount = 0;
        String[] ss = noCnWords.split(" ");
        for (String s : ss) {
            if (s.trim().length() != 0) {
                noCnWordsCount++;
            }
        }
        //中文和非中文单词合计
        return cnWordsCount + noCnWordsCount;
//
//        int words_count = 0;
//        //中文单词
//        String cn_words = context.replaceAll("[^(\\u4e00-\\u9fa5，。《》？；’‘：“”【】、）（……￥！·)]", "");
//        int cn_words_count = cn_words.length();
//        //非中文单词
//        String non_cn_words = context.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":><?\\[\\])]", " ");
//        int non_cn_words_count = 0;
//        String[] ss = non_cn_words.split(" ");
//        for (String s : ss) {
//            if (s.trim().length() != 0) non_cn_words_count++;
//        }
////中文和非中文单词合计
//        words_count = cn_words_count + non_cn_words_count;
////        ToolLog.d(ConstString.TAG, "汉字：" + cn_words_count + "\n\t字符：" + non_cn_words_count);
//        return words_count;
    }

     public static void readAndWriterTest3(String path) throws IOException {
              File file = new File(path);
              String str = "";
              try {
                    FileInputStream fis = new FileInputStream(file);
                    HWPFDocument doc = new HWPFDocument(fis);
                    String doc1 = doc.getDocumentText();
                    System.out.println(doc1);
                    StringBuilder doc2 = doc.getText();
                     System.out.println(doc2);
                     Range rang = doc.getRange();
                     String doc3 = rang.text();
                     System.out.println(doc3);
                     fis.close();
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
        }
    /**
     * POI 读取word文件内容
     * @param path 文件路径
     * @return 文件内容字符串
     */
    public static String readWord(String path) {
        String buffer = "";
        try {
            if (path.endsWith(".doc")) {
                InputStream is = new FileInputStream(new File(path));
                WordExtractor ex = new WordExtractor(is);
                buffer = ex.getText();

            } else if (path.endsWith("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
//                extractor.close();
            } else {
                System.out.println("此文件不是word文件！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer;
    }


    static int[] wordCountNew(String doc, boolean isDebug) throws Exception {
        long time = System.currentTimeMillis();
        InputStream is = new FileInputStream(new File(doc));
        WordExtractor ex = new WordExtractor(is);
        int cnt = 0;
        int sumCount = 0;//统计总字符数
        StringBuilder builder = new StringBuilder();
        for (String text : ex.getParagraphText()) {
//            text = text.replaceAll("\u0007", "").replaceAll("\f", "")
//                    .replaceAll("\r", "").replaceAll("\n", "")
//                    .replaceAll("\u0015", "");
            if (isDebug) {
                text = trimAllChars(text, new char[] { '\u0007', '\f', '\b', '\u0015' });
            } else {
                text = trimAllChars(text, new char[] { '\u0007', '\f', '\b', '\u0015', '\r', '\n' });
            }

            String prefix = " TOC \\o \\u \u0014";
            if (text.startsWith(prefix))
                text = text.substring(prefix.length());
//            flag = "\u0013 EMBED Visio.Drawing.11 \u0014\u0001";
//            flag = "\u0013 EMBED Word.Document.12 \\s \u0014\u0001";
            int start = text.indexOf("\u0013");
            int end = text.indexOf("\u0014\u0001");
            if (start >= 0 && end > start) {
                text = text.replaceAll("\u0013[^\u0014\u0001]+\u0014\u0001", "");
            }
            text = text.replaceAll("\u0013[^\u0014\u0013]+\u0014", "");

            String flag = "\u0013 HYPERLINK";
            int pos = text.indexOf(flag);
            if (pos >= 0) {
                String[] arr = text.split(" \u0014");
                text = text.substring(0, pos) + arr[1];
            }

            if (text.length() >= 767) {
                // word doc格式时, 如果连续字符数数大于767个(大于等于768), 则该段落的字数不计入
//                if (text.replaceAll(" ", "").length() < text.length() - 767) { //
                text = text.replaceAll(" {767,}", "");
//                }
            }

            if (isDebug)
                builder.append(text);
            cnt += text.length();
            sumCount +=text.split(" ").length;
        }

        int t = Long.valueOf(System.currentTimeMillis() - time).intValue();

        if (isDebug) {
            System.out.println(builder.toString()); // .replaceAll("\r", "").replaceAll("\n", "")
            System.out.println(cnt);
            System.out.println(t + " ms");
        }
        return new int[] { cnt, sumCount,t };
    }

    private static String trimAllChars(String text, char[] chars) {
        if (text == null || text.isEmpty())
            return text;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            if (!ArrayUtils.contains(chars, text.charAt(i)))
                builder.append(text.charAt(i));
        }
        return builder.toString();
    }
}
